package com.muyu.file.service.impl;

import com.muyu.file.service.ConvertBaseService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;

/**
 * ConvertBaseServiceImpl
 *
 * @author LeYang
 * on 2025/3/17
 */
@Service
public class ConvertBaseServiceImpl implements ConvertBaseService {
    @Override
    public String base64(MultipartFile multipartFile) {
        try {
            byte[] bytes = multipartFile.getBytes();
            String base64Encoded = Base64.getEncoder().encodeToString(bytes);
            String contentType = multipartFile.getContentType();
            if (contentType == null || contentType.equals("application/octet-stream")) {
                String fileName = multipartFile.getOriginalFilename();
                if (fileName != null) {
                    int lastIndex = fileName.lastIndexOf('.');
                    if (lastIndex != -1) {
                        String fileExtension = fileName.substring(lastIndex + 1).toLowerCase();
                        switch (fileExtension) {
                            case "jpg":
                            case "jpeg":
                                contentType = "image/jpeg";
                                break;
                            case "png":
                                contentType = "image/png";
                                break;
                            case "gif":
                                contentType = "image/gif";
                                break;
                            case "bmp":
                                contentType = "image/bmp";
                                break;
                            case "webp":
                                contentType = "image/webp";
                                break;
                            default:
                                contentType = "image/png";
                        }
                    }
                }
            }
            return "data:" + contentType + ";base64," + base64Encoded;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
